package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    //登录
    @Override
    public ResultInfo login(String username, String password) {
        //通过名字查询
        Employee employee = employeeMapper.loginByUserName(username);
        //判断是否为空
        if (employee == null) {
//            return ResultInfo.error("账号不存在");
            throw new CustomException("账号不存在");
        }
        if (employee.getStatus() != 1) {
//            return ResultInfo.error("账号未激活");
            throw new CustomException("账号未激活");
        }
        //密码加密
        String passwordWithMd5 = SecureUtil.md5(password);
        String employeePassword = employee.getPassword();
        //判断密码是否正确
        if (!StringUtils.equals(passwordWithMd5,employeePassword)) {
//            return ResultInfo.error("密码错误");
            throw new CustomException("密码错误");
        }
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        List<Employee> employeeList = employeeMapper.findByName(name);
        return employeeList;
    }

    @Override
    public void save(Employee employee) {
        //补齐参数
        //利用雪花算法生成唯一id
        employee.setId(IdUtil.getSnowflake(1,1).nextId());
        //生成默认密码
        String password = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(password);
        //设置激活状态
        employee.setStatus(Employee.STATUS_ENABLE);
//        //创建 修改时间
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
//        //创建 修改用户
//        employee.setCreateUser(1L);//临时写死
//        employee.setUpdateUser(1L);//临时写死

        //调用方法
        employeeMapper.save(employee);

    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }

    @Override
    public void update(Employee employee) {
//        //设置修改时间
//        employee.setUpdateTime(new Date());
//        //设置修改用户
//        employee.setUpdateUser(1L);//临时设死
        //调用方法
        employeeMapper.update(employee);
    }
}
